package com.book.service.impl;

import com.book.dto.UserManageDto;
import com.book.entity.User;
import com.book.format.Result;
import com.book.format.ResultUtil;
import com.book.page.Page;
import com.book.service.UserService;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * Created by Mikey on 2017/6/10.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    private String USERMAPPER = "com.book.mapper.UserMapper";

    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    public Result getUserList(Page page){
        Integer count = sqlSessionTemplate.selectOne(USERMAPPER+".selectCount");
        List<UserManageDto> users = sqlSessionTemplate.selectList(USERMAPPER+".selectUserManage",page);
        Map map = new HashMap();
        map.put("count",count);
        map.put("users",users);
        return ResultUtil.success(map);
    }

    public Result deleteUser(String uid){
        Map map = new HashMap();
        map.put("uid",uid);
        Integer i = sqlSessionTemplate.delete(USERMAPPER+".deleteUser",map);
        return ResultUtil.success(i);
    }

    public Result addOrEditUser(User user){
        Integer i;
        if("".equals(user.getU_id())){
            user.setU_id(UUID.randomUUID().toString());
            i = sqlSessionTemplate.insert(USERMAPPER+".addUser",user);
        }else{
            i = sqlSessionTemplate.update(USERMAPPER+".updateUser",user);
        }
        return ResultUtil.success(i);
    }

    public Result excelUser(String id) {
        return null;
    }
}
